package services;

import com.fasterxml.jackson.databind.JsonNode;
import dao.TruckInfo_Repository;
import models.*;
import org.apache.commons.collections.CollectionUtils;
import play.db.jpa.JPAApi;

import javax.inject.Inject;
import javax.persistence.Query;
import java.sql.Timestamp;
import java.util.List;
import java.util.concurrent.CompletionStage;

import static java.util.concurrent.CompletableFuture.supplyAsync;


/**
 * Provide JPA operations running inside of a thread pool sized to the connection pool
 */
public class TruckInfo_Repository_JPA implements TruckInfo_Repository {

    private final JPAApi jpaApi;
    private final DatabaseExecutionContext executionContext;

    @Inject
    public TruckInfo_Repository_JPA(JPAApi jpaApi, DatabaseExecutionContext executionContext) {
        this.jpaApi = jpaApi;
        this.executionContext = executionContext;
    }

    /*
        @Override
        public CompletionStage<TDeptInfoEntity> getDeptByID (Integer DeptID)
        {
            return supplyAsync(() -> {
                return jpaApi.withTransaction(entityManager -> {
                    Query query = entityManager.createQuery("select d from TDeptInfoEntity d where d.fdDeptId = :DeptID ", TDeptInfoEntity.class).setParameter("DeptID", DeptID);
                    TDeptInfoEntity _tDeptInfoEntity = new TDeptInfoEntity();
                    if(query.getResultList().size() > 0)
                    {
                        _tDeptInfoEntity = (TDeptInfoEntity)query.getResultList().get(0);
                    }
                    else
                    {
                        // 单位不存在等“异常”情况，仍然以结构返回。但返回为0
                        _tDeptInfoEntity.setFdDeptId(0);
                    }

                    return _tDeptInfoEntity;
                });
            }, executionContext);
        }
     */
    @Override
    public CompletionStage<List<TruckInfo_C_Entity>> getTruckList(String PhoneNumber) {
        return supplyAsync(() -> {
            return jpaApi.withTransaction(entityManager -> {
//            	TruckInfo_T_Entity _truckInfo_T_Entity = new TruckInfo_T_Entity();
//            	return entityManager.createQuery("select new vo.TruckInfo_C_Entity(t.fdRowId, t.fdDeptId, t.fdLoadCapacity, t.fdTruckLength, t.fdTruckWidth, t.fdTruckHeight, t.fdModifiedDate, t.fdTruckNumber, t.fd_Type, t.fd_GpsEqptNo, t.fd_SIMNO, t.fd_GPSProvider, d.fdDeptName, t.fd_Gps) from TruckInfo_T_Entity t ,DeptInfo_T_Entity d where t.fdDeptId = d.fdDeptId order by t.fdDeptId", TruckInfo_C_Entity.class).getResultList();
                String strSql = "select * from dbo.f_getTruckList('" + PhoneNumber + "')";
                return entityManager.createNativeQuery(strSql, TruckInfo_C_Entity.class).getResultList();
            });
        }, executionContext);
    }

    @Override
    public CompletionStage<String> addTruckNo(JsonNode DeptIds, JsonNode LoadCapacitys, JsonNode PlateNos, JsonNode TruckTypes) {
        return supplyAsync(() -> {
            return jpaApi.withTransaction(entityManager -> {
                if (DeptIds.size()<=0||LoadCapacitys.size()<=0|| PlateNos.size()<=0||TruckTypes.size()<=0) {

                    return "请填写正确信息";
                }

                for (int i = 0; i < DeptIds.size(); i++) {

                    String DeptId = DeptIds.get(i).toString().replace("\"","");
                    String LoadCapacity = LoadCapacitys.get(i).toString().replace("\"","");
                    String TruckNumber = PlateNos.get(i).toString().replace("\"","");
                    String Type =  TruckTypes.get(i).toString().replace("\"","");
                    List<TruckInfo_C_Entity> listTruck = entityManager.createQuery("select t from TruckInfo_T_Entity t where t.fdTruckNumber = :fdTruckNumber and t.fdDeptId = :fdDeptId").setParameter("fdTruckNumber", TruckNumber).setParameter("fdDeptId", Integer.valueOf(DeptId)).getResultList();

                    if (CollectionUtils.isNotEmpty(listTruck)) {
                        return "车辆"+TruckNumber+"已经存在，请勿重新添加";
                    }
                    String strSql = "insert into dbo.t_TruckInfo([fd_TruckNumber],[fd_DeptID],[fd_loadCapacity],[fd_Type],[fd_ModifiedDate])values('" + TruckNumber + "','"
                            + DeptId + "','"
                            + LoadCapacity + "','"
                            + Type + "','"+new Timestamp(System.currentTimeMillis()).toString()+"')";
                    entityManager.createNativeQuery(strSql).executeUpdate();
                }
                return "车辆添加成功";
            });
        }, executionContext);
    }

    @Override
    public CompletionStage<List<GeometryDesc_T_Entity>> areaList() {
        return supplyAsync(() -> {
            return jpaApi.withTransaction(entityManager -> {
                String strSql = "SELECT fd_RowId,fd_Desc,fd_AreaType,fd_MapSource FROM t_GeometryDesc";
                return entityManager.createNativeQuery(strSql, GeometryDesc_T_Entity.class).getResultList();
            });
        }, executionContext);
    }

    public CompletionStage<List<TruckInfo_NT_Entity>> truckById(Integer TruckId) {
        return supplyAsync(() -> {
            return jpaApi.withTransaction(entityManager -> {
                String strSql = "SELECT * FROM t_TruckInfo where fd_RowID = '" + TruckId + "'";
                return entityManager.createNativeQuery(strSql, TruckInfo_NT_Entity.class).getResultList();
            });
        }, executionContext);
    }

    public CompletionStage<List<TruckInfo_NT_Entity>> truckByDeptIds(String DeptIds) {
        return supplyAsync(() -> {
            return jpaApi.withTransaction(entityManager -> {
                String strSql = "SELECT * FROM t_TruckInfo where fd_DeptID in (select * from dbo.f_SplitString('" + DeptIds + "',',')) ";
                return entityManager.createNativeQuery(strSql, TruckInfo_NT_Entity.class).getResultList();
            });
        }, executionContext);
    }

    @Override
    public CompletionStage<List<TruckInfo_NT_Entity>> truckByAreaNames(String AreaNames) {
        return supplyAsync(() -> {
            return jpaApi.withTransaction(entityManager -> {
                String strSql = "SELECT * FROM t_TruckInfo where t_TruckInfo.fd_LastPosi in (select * from dbo.f_SplitString('" + AreaNames + "',',')) ";
                return entityManager.createNativeQuery(strSql, TruckInfo_NT_Entity.class).getResultList();
            });
        }, executionContext);
    }

    @Override
    public CompletionStage<List<TruckInfo_NT_Entity>> truckByAreaIds(String AreaIds, String PhoneNumber) {
        return supplyAsync(() -> {
            return jpaApi.withTransaction(entityManager -> {
                String strSql = "select * from dbo.f_truckByAreaIds('" + AreaIds + "','" + PhoneNumber + "') ";
                return entityManager.createNativeQuery(strSql, TruckInfo_NT_Entity.class).getResultList();
            });
        }, executionContext);
    }

    @Override
    public CompletionStage<String> ModifyTruckType(String PlateNo,String type) {
        return supplyAsync(() -> {
            return jpaApi.withTransaction(entityManager -> {
                Query query = entityManager.createQuery("update TruckInfo_T_Entity t set t.fd_Type ='"+Integer.valueOf(type)+"' where t.fdTruckNumber =:fdTruckNumber");
                query.setParameter("fdTruckNumber",PlateNo);
                query.executeUpdate();

                return "修改成功";
            });
        }, executionContext);
    }

    @Override
    public CompletionStage<String> DeleteTruck(String PlateNo) {
        return supplyAsync(() -> {
            return jpaApi.withTransaction(entityManager -> {
                Query query = entityManager.createQuery("update TruckInfo_T_Entity t set t.deleted = 1 where t.fdTruckNumber =:fdTruckNumber");
                query.setParameter("fdTruckNumber",PlateNo);
                query.executeUpdate();

                return "删除成功";
            });
        }, executionContext);
    }
}